<!--
 * @Author: daidai
 * @Date: 2022-03-01 11:17:39
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2022-09-29 15:50:18
 * @FilePath: \web-pc\src\pages\big-screen\view\indexs\center-map.vue
-->
<template>
  <div class="centermap">
    <div class="maptitle">
      <div class="zuo"></div>
      <span class="titletext">实验室监控</span>
    </div>
    <div class="select-box">
      <select @change="pickMonitoring" v-model="monitoringNum">
        <option value="0">请选择实验室房间号</option>
        <option value="1">1号房间</option>
      </select>
      <img class="icon" src="../../assets/img/custom/down.svg" />
    </div>
    <div class="mapwrap">
      <dv-border-box-1>
        <div class="plugin-box">
          <div id="divPlugin" class="plugin"></div>
        </div>
      </dv-border-box-1>
    </div>
  </div>
</template>

<script>
// import {
//   setAccountSecret,
//   getAccountSecret,
//   delAccountSecret,
// } from "@/api/lifetimes/monitoringCenter.js"
// import { getSafeDevice } from "@/api/lifetimes/safedevice.js"
export default {
  data() {
    return {
      monitoringNum: 0,
      fullscreenLoading: false,
      szDeviceIdentify: "",
      isError: false,
      loginForm: {
        account: "",
        password: "",
        ip: "",
        sort: "",
      },
      loginDialogVisible: false,
      safeDeviceList: [],
      currentDevice: {
        deviceName: "",
        ip: "",
        status: "",
        statusName: "",
        installationSiteName: "",
      },
    }
  },
  mounted() {
    this.getSafeDeviceList()
  },
  async destroyed() {
    await this.I_Stop()
    await WebVideoCtrl.I_Logout(this.szDeviceIdentify)
    await WebVideoCtrl.I_DestroyPlugin()
  },
  methods: {
    pickMonitoring(e) {
      console.log(e)
    },
    async getSafeDeviceList() {
      const res = await getSafeDevice({ pageNum: 1, pageSize: 9999 })
      console.log("safeDeviceList", res)
      if (res.rows) {
        this.safeDeviceList = res.rows
        this.currentDevice = res.rows[0]
      }
      this.getDeviceInfo()
    },
    //获取监控信息
    async getDeviceInfo() {
      const res = await getAccountSecret({})
      console.log("res=", res)
      if (res.data) {
        this.loginForm = res.data
        this.szDeviceIdentify = this.loginForm.ip + "_" + this.loginForm.sort
        this.init()
      } else {
        // this.loginDialogVisible = true;
        alert("无法识别到设备信息，请先前往至安防设备列表进行同步！")
        this.$router.push("/lifetimes/deviceManagement/safeDevice")
      }
    },
    //设置监控信息
    async saveSetting() {
      const res = await setAccountSecret(this.loginForm)
      console.log("shezhi", res)
      this.loginDialogVisible = false
      this.szDeviceIdentify = this.loginForm.ip + "_" + this.loginForm.sort
      this.init()
    },
    I_Stop() {
      return new Promise((resolve, reject) => {
        WebVideoCtrl.I_Stop({
          success() {
            resolve()
          },
        })
      })
    },
    //切换摄像头
    changeDevice(item) {
      const _this = this
      this.currentDevice = item
      console.log("555", item)
      if (this.isError) {
        WebVideoCtrl.I_StartRealPlay(_this.szDeviceIdentify, {
          iStreamType: 1, //码流类型 1-主码流，2-子码流，默认使用主码流预览
          iChannelID: Number(item.channel), //播放通道号，默认通道 1
          bZeroChannel: false, //是否播放零通道，默认为 false
          iWndIndex: 0, //播放窗口，如果不传，则默认使用当前选择窗口播放（默认选中窗口 0）
          success: function () {
            console.log("开始预览成功！")
            _this.$message.success("切换成功")
            _this.isError = false
          },
          error: function (oError) {
            console.log("开始预览失败！")
            _this.isError = true
          },
        })
      } else {
        WebVideoCtrl.I_Stop({
          success: function () {
            WebVideoCtrl.I_StartRealPlay(_this.szDeviceIdentify, {
              iStreamType: 1, //码流类型 1-主码流，2-子码流，默认使用主码流预览
              iChannelID: Number(item.channel), //播放通道号，默认通道 1
              bZeroChannel: false, //是否播放零通道，默认为 false
              iWndIndex: 0, //播放窗口，如果不传，则默认使用当前选择窗口播放（默认选中窗口 0）
              success: function () {
                console.log("开始预览成功！")
                _this.$message.success("切换成功")
                _this.isError = false
              },
              error: function (oError) {
                console.log("开始预览失败！")
                _this.isError = true
              },
            })
            console.log("开始播放")
          },
        })
      }
    },
    //初始化
    init() {
      const _this = this
      this.fullscreenLoading = true
      console.log("init")
      // 初始化插件参数及插入插件
      WebVideoCtrl.I_InitPlugin({
        bWndFull: true, //是否支持单窗口双击全屏，默认支持 true:支持 false:不支持
        iWndowType: 1,
        bDebugMode: true,
        cbSelWnd: function (xmlDoc) {},
        cbDoubleClickWnd: function (iWndIndex, bFullScreen) {},
        cbEvent: function (iEventType, iParam1, iParam2) {},
        cbInitPluginComplete: function () {
          WebVideoCtrl.I_InsertOBJECTPlugin("divPlugin").then(
            () => {
              // 检查插件是否最新
              WebVideoCtrl.I_CheckPluginVersion().then(bFlag => {
                if (bFlag) {
                  alert("检测到新的插件版本，双击开发包目录里的HCWebSDKPlugin.exe升级！")
                }
              })
            },
            () => {
              _this.fullscreenLoading = false
              alert(
                "插件初始化失败，即将为您自动下载HCWebSDKPlugin.exe插件,下载成功后双击安装即可使用!"
              )

              window.location.href = "./hk/HCWebSDKPlugin.exe"
            }
          )
        },
      })

      // 窗口事件绑定
      $(window).bind({
        resize: function () {
          WebVideoCtrl.I_Resize($("#divPlugin").width(), $("#divPlugin").height())
        },
      })

      //初始化日期时间
      // var szCurTime = dateFormat(new Date(), "yyyy-MM-dd");
      // $("#starttime").val(szCurTime + " 00:00:00");
      // $("#endtime").val(szCurTime + " 23:59:59");
      // $("#downloadstarttime").val(szCurTime + " 00:00:00");
      // $("#downloadendtime").val(szCurTime + " 23:59:59");

      setTimeout(() => {
        this.login()
      }, 1000)
    },
    // 开始预览
    startRealPlay() {
      this.fullscreenLoading = false
      WebVideoCtrl.I_StartRealPlay(this.szDeviceIdentify, {
        iStreamType: 1, //码流类型 1-主码流，2-子码流，默认使用主码流预览
        iChannelID: this.currentDevice.channel, //播放通道号，默认通道 1
        bZeroChannel: false, //是否播放零通道，默认为 false
        iWndIndex: 0, //播放窗口，如果不传，则默认使用当前选择窗口播放（默认选中窗口 0）
        success: function () {
          console.log("开始预览成功！")
        },
        error: function (oError) {
          console.log("开始预览失败！")
        },
      })
      console.log("开始播放")
    },
    login() {
      const _this = this
      const { account, password, ip, sort } = this.loginForm
      WebVideoCtrl.I_Login(ip, 1, sort, account, password, {
        timeout: 3000,
        success: async function (xmlDoc) {
          console.log("登录成功！")
          await _this.getChannelInfo()
          await _this.getDevicePort()
          await _this.startRealPlay()
        },
        error: async function (oError) {
          console.log("登录失败！", oError)
          if (oError.errorCode == 2001) {
            //重复登录
            await _this.getChannelInfo()
            await _this.getDevicePort()
            await _this.startRealPlay()
          } else {
            // 关闭插件
            WebVideoCtrl.I_DestroyPlugin()
            _this.fullscreenLoading = false
            alert("无法识别到设备信息，请先前往至安防设备列表进行同步！")
            _this.$router.push("/lifetimes/deviceManagement/safeDevice")
          }
        },
      })
    },
    I_GetAnalogChannelInfo() {
      new Promise((resolve, reject) => {
        // 模拟通道
        WebVideoCtrl.I_GetAnalogChannelInfo(this.szDeviceIdentify, {
          success: function (xmlDoc) {
            console.log("获取模拟通道成功！", xmlDoc)
            resolve()
          },
          error: function (oError) {
            console.log("获取模拟通道失败！")
            resolve()
          },
        })
      })
    },
    I_GetDigitalChannelInfo() {
      const _this = this
      new Promise((resolve, reject) => {
        // 数字通道
        WebVideoCtrl.I_GetDigitalChannelInfo(this.szDeviceIdentify, {
          success: function (xmlDoc) {
            // const res = _this.xmlTransformObject(xmlDoc.children[0]);
            // console.log("xmlTransformObject=", res);
            console.log("获取数字通道成功！", xmlDoc)
            resolve()
          },
          error: function (oError) {
            console.log("获取数字通道失败！")
            resolve()
          },
        })
      })
    },
    I_GetZeroChannelInfo() {
      new Promise((resolve, reject) => {
        // 零通道
        WebVideoCtrl.I_GetZeroChannelInfo(this.szDeviceIdentify, {
          success: function (xmlDoc) {
            console.log("获取零通道成功！", xmlDoc)
            resolve()
          },
          error: function (oError) {
            console.log("获取零通道失败！")
            resolve()
          },
        })
      })
    },
    // 获取通道
    getChannelInfo() {
      return new Promise((resolve, reject) => {
        Promise.all([
          this.I_GetAnalogChannelInfo(),
          this.I_GetDigitalChannelInfo(),
          this.I_GetZeroChannelInfo(),
        ])
          .then(res => {
            resolve()
          })
          .catch(() => {
            resolve()
          })
      })
    },
    // 获取端口
    getDevicePort() {
      return new Promise((resolve, reject) => {
        WebVideoCtrl.I_GetDevicePort(this.szDeviceIdentify).then(
          oPort => {
            console.log("获取端口成功！")
            resolve()
          },
          oError => {
            console.log("获取端口失败！")
            resolve()
          }
        )
      })
    },
  },
}
</script>
<style lang="scss" scoped>
.plugin-box {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  .plugin {
    width: 96%;
    height: 93%;
  }
}

.centermap {
  .select-box {
    width: 100%;
    text-align: right;
    margin-bottom: 15px;
    position: relative;
    select {
      appearance: none;
      -webkit-appearance: none;
      border: 0;
      width: 247px;
      height: 41px;
      border: 1px solid #1186b8;
      background-color: rgb(9, 16, 50);
      color: #5dc0ff;
      font-size: 14px;
      border-radius: 4px;
      outline: none;
      box-sizing: border-box;
      padding: 10px;
    }
    .icon {
      position: absolute;
      right: 10px;
      top: 50%;
      transform: translateY(-50%);
      width: 30px;
      height: 20px;
    }
  }
  .maptitle {
    width: 100%;
    height: 60px;
    display: flex;
    justify-content: center;
    padding-top: 10px;
    box-sizing: border-box;
    position: relative;

    .titletext {
      font-size: 28px;
      font-weight: 900;
      letter-spacing: 6px;
      background: linear-gradient(92deg, #0072ff 0%, #00eaff 48.8525390625%, #01aaff 100%);
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;
      margin: 0 10px;
    }

    .zuo,
    .you {
      background-size: 100% 100%;
      width: 29px;
      height: 20px;
      margin-top: 8px;
    }

    .zuo {
      background: url("../../assets/img/xiezuo.png") no-repeat;
    }

    .you {
      background: url("../../assets/img/xieyou.png") no-repeat;
    }
  }

  .mapwrap {
    height: 548px;
    width: 100%;
    // padding: 0 0 10px 0;
    box-sizing: border-box;
    position: relative;
  }
}
</style>
